<?php
/**
* fmdc操作
*/
class fmdc
{
    //**** 定义私有变量 ****//

        // 用户信息相关
        private $userName;          // 用户账号
        private $password;          // 用户密码
        private $userCookies;       // 登录Cookies
        private $status = 0;        // 状态

        // 定义错误信息
        private $errorMsg;          // 错误信息

        // 系统选项相关
        private $options = array(
            'recordsFile' => './userRecords.json',   // 记录用户信息的文件
        );    
        //  文章默认选填参数
        private $postOptionss = array(
				'id'=>0,
				'hid' => '', 
				'Title'=>true,
				'PublishDate'=>true,
				'ShortTitle'=>true,
				'keyword'=>true,
				'Remark'=>true,
				'uploadType'=>8,
				'content'=>true,
        );
     
    /**
     * 初始化函数
     * @param string $userName    用户账号
     * @param string $password    用户密码
     * @param string $userCookies 登录Cookies
     * @param array  $options     配置选项信息
     */
    function __construct($userName, $password, $userCookies = null, $options = array())
    {  	
        $this->userName = $userName;  // 保存用户账号
        $this->password = $password;  // 保存用户密码

        // 识别并保存配置选项
        foreach ($options as $optKey => $optValue)
            $this->options[$optKey] = $optValue;

        // 检查保存用户信息的文件
        file_exists($this->options['recordsFile']) ?: file_put_contents($this->options['recordsFile'], '{}');

        // 设置并保存Cookies
        if(!$userCookies){
            $userRecords = json_decode(file_get_contents($this->options['recordsFile']), true);
            if(!empty($userRecords[$this->userName]['Cookies']))
                $userCookies = $userRecords[$this->userName]['Cookies'];
        }

        $this->setCookie($userCookies) ?: $this->errorMsg = 'NotLogin';
    }

    /**
     * 获取上次操作的错误信息
     * @return string 错误信息描述
     */
    public function getErrorMsg()
    {
        return $this->errorMsg;
    }

    /**
     * 设置并验证用户Cookies
     * @param string $cookies 用户Cookies
     */
    public function setCookie($cookies = null)
    {
        // 验证登录的地址
        $url = 'http://yykht.bj.familydoctor.com.cn';

        // 提交请求
        $retHtml = Get_Web_Contents($url, 'GET', '',$cookies);
        
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错';
            return false;
        }

        // 判断是否已经登录 
        $regEx = '#<input id="(?<type>[^"]+)" name="(?<name>[^"]+)"[^>]+/>#';
        preg_match_all($regEx, $retHtml['Body'], $val);
        if(empty($val)){
        	$this->userCookies = $cookies;
        	$this->status      = 1;
        	return true;
        } else {
        	$this->status   = 0;
        	$this->errorMsg = '账号未登录';
        	return false;
         }
    }

    /**
     * 保存用户的Cookies
     */
    public function saveCookie()
    {
        if($this->status <= 0) {
            $this->errorMsg = '登录状态不正确';
            return false;
        }
        $userRecords = json_decode(file_get_contents($this->options['recordsFile']), true);
        $userRecords[$this->userName]['Cookies'] = $this->userCookies;
        if(!file_put_contents($this->options['recordsFile'], json_encode($userRecords))){
            $this->errorMsg = '保存到json文件失败';
            return false;
        }
        return true;
    }

    /**
     * 用户账号登录
     * @param  string $userName 需要登录的用户账号
     * @param  string $password 需要登录的用户密码
     * @return mixed            登录成功返回用户Cookies 失败返回 false
     */
    public function userLogin($userName = null, $password = null)
    {
        // 设置账号密码
        $userName ?: $userName = $this->userName;
        $password ?: $password = $this->password;

        // 登录提交的地址
        $url = 'http://yykht.bj.familydoctor.com.cn/home/Login';

        // 获取登录表单信息
        $retHtml = Get_Web_Contents($url);
        if(empty($retHtml['Body'])){
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }
        // 匹配表单字段名 
        $regEx = '#<input id="(?<type>[^"]+)" name="(?<name>[^"]+)"[^>]+/>#';
        if(!preg_match_all($regEx, $retHtml['Body'], $formInfo)) {
            $this->errorMsg = '匹配表单字段名失败.';
            return false;
        }

        // 生成表单信息      
        $data="";
        foreach ($formInfo['type'] as $key => $type) {
            switch ($type) {
                case 'userName':
                    $data.= "{$formInfo['name'][$key]}={$userName}&";
                    break;
                case 'password':
                    $data.= "{$formInfo['name'][$key]}={$password}&";
                    break;
                default:
                    # code...
                    break;
            }
        }
    
        // 提交登录数据    
        $retHtml = Get_Web_Contents($url, 'POST', $data ,$retHtml['Cookies']);    
        if(isset($retHtml['Error'])) {
            $this->errorMsg = 'cUrl请求时出错.';
            return false;
        }
        // 判断登录没有
        $json= $retHtml['Body'];
        $yes=json_decode($json, true)["Success"];
        if(empty($yes)){
        	$this->errorMsg = "登录失败了";
        	return false;
        }
        
        $this->userCookies = $retHtml['Cookies'];
        $this->status      = 1;
        return $retHtml['Cookies'];
    }  
    /**
     * 发布文章
     * @param  string  $title    文章标题
     * @param  string  $body     文章内容
     * @param  integer $classID  分类ID(全站)
     * @param  integer $columnID 栏目ID(本站)
     * @param  array   $options  其他选项
     * @return [type]           [description]
     */
    public function postAddproduct($title, $userList)
    {
    	$markName = $userList['mark'];
    	$postArr  = getDalArticle($markName);
    	$postInfo = $postArr['0'];

    	// 字符串替换
    	
    	$postInfoproduct['body'] = postBodyReplace($postInfo['body'], $userList['hosType'], $title);
    	// 末尾追加发布时间
    	$summary = postnewssummary($postInfoproduct['body']);
    	$postInfoproduct['body'].= "<p>".date('YmdHis')."</p>";
    	
    	$url = 'http://yykht.bj.familydoctor.com.cn/case/create';
    
    	// 获取页面内容用来提取表单字段名
    	$retHtml = Get_Web_Contents($url, 'GET', '', $this->userCookies);
    	if(isset($retHtml['Error'])) {
    		$this->errorMsg = 'cUrl请求时出错.';
    		return false;
    	}
  
    	// 获取表单正文
    	$regEx = '#<form[^>]+>(?<form>.*?)</form>#s';
    	if(!preg_match($regEx, $retHtml['Body'], $formBody)){
    		// 先检查是否频繁
    		$this->errorMsg = '提取表单正文时失败.';
    		if(stripos($retHtml['Body'], '休息一会')){
    			
    			$this->errorMsg = '操作频繁';
    		}
    		return false;
    	}
    
    	// 获取表单字段
    	$regEx = '#name="(?<name>[^"]+)"#';
    	if(!preg_match_all($regEx, $formBody['form'], $formList)){
    		$this->errorMsg = '提取表单字段列表时出错.';
    		return false;
    	}
    	$formList = $formList['name'];
    	// 修改值
    	$this->postOptionss['Title']      =$title;      // 文章标题
    	$this->postOptionss['PublishDate']      = date('Y-m-d H:i:s');      //时间
    	$this->postOptionss['ShortTitle']      = $title;      //短标语
    	$this->postOptionss['keyword']      = $title;      //关键词
    	$this->postOptionss['Remark']      = $summary;      // 摘要
    	$this->postOptionss['content']      = $postInfoproduct['body'];      //文章内容
    	// 重新整理值关系
    	$i = 0;$postData = array();
    	foreach ($this->postOptionss as $key => $value) {
    		$name = $formList[$i++];
    		$postData[$name] = $value;
    	}
    	$URL="http://yykht.bj.familydoctor.com.cn/PopularArticle/Create";
    	$retHtmls = Get_Web_Contents($URL, 'POST', http_build_query($postData), $this->userCookies);
    	if(isset($retHtmls['Error'])) {
    		$this->errorMsg = 'cUrl请求时出错.';
    		return false;
    	}  
  
    	// 判断是否成功
       $json= $retHtmls['Body'];
       $yes=json_decode($json, true)["Success"];
        if(empty($yes)){
            $this->errorMsg = json_decode($json, true)["Errors"];
            return false;
        }else{
        	return true;
        }
   
    }
    
    /**
     * 获取文章列表
     * @param  integer $page 页码
     * @return array         所有地址
     */
    public function getPostList($list = 1)
    {
    	
    	//获取产品的链接
	    	$url = "http://yykht.bj.familydoctor.com.cn/PopularArticle/Index?page=1";    	
	        // 读取页面内容
	        $retHtml = Get_Web_Contents($url, 'GET', '', $this->userCookies);	        
	        $retHtml['Body'] = str_ireplace(array("\r\n","\t", "\r","\n"), '', $retHtml['Body']);        
	        $date = date('Y/n/j');
	        $regEx = '#<td class="id">(?<id>.*?)</td>(.*?)title="(?<title>[^"]+)"(.*?)'.$date.'#s';	
	        
	        //取今日发布的id title  
	        preg_match_all($regEx, $retHtml['Body'], $val);
	        if(empty($val)){	    
	        	$this->errorMsg = '提取id和Title列表时出错.';
	        	return false;
	        }
	       		//将id拼接成链接
	            foreach ($val['id'] as $key => $value) {
		        //产品webhttp://yyk.familydoctor.com.cn/20921/Content_395746.html
		         $retList['site'][$key]  = 'http://yyk.familydoctor.com.cn/20921/Content_'.$value.'.html';
	      
                }
                //将title和id组合成一个数组
                foreach ($val['title'] as $key => $value) {
                	$retList['title'][$key]  = $value;
                	 
                }
 
               return $retList;
    }

	//获取发布文章的所有URL 和 标题 列表
	function savePostUrl_Title($userName,$postList,$i){
		
		$saveErro = "";
		$title = $site = $titleList = array();//初始化
		$site  = $postList['site'];
		$title = $postList['title'];
		$len   = count($site);
		$url = "http://yykht.bj.familydoctor.com.cn/PopularArticle/Index?page={$i}";
		$contents = Get_Web_Contents($url, 'GET', '', $this->userCookies);// 读取页面内容
		if (!$contents['Body']) print_r("{$userName}··· 没有读取到页面内容\n");
        
        //每日记录
//          file_put_contents(POST_URL_KEY_LIST.'log/'.date('m-d').".csv", $userName."\n" , FILE_APPEND);
        $contents['Body'] = str_ireplace(array("\r\n","\t", "\r","\n"), '', $contents['Body']);
        
		for($j=0; $j<$len; $j++){
 			
			//获取关键词（标题）

			$titleList[] = $title[$j];
			$temp = array($site[$j],$title[$j]);
			$hash = implode(",",$temp);
			unset($temp);
			$res = file_put_contents(POST_URL_KEY_LIST.$userName.".csv", $hash."\n", FILE_APPEND);
            
            //每日记录
// 			file_put_contents(POST_URL_KEY_LIST.'log/'.date('m-d').".csv", $hash."\n", FILE_APPEND);
			if (!$res) $saveErro = true;
		}
		
		$json_titleList = json_encode($titleList); 
		return ($saveErro === true) ? false : $json_titleList;
	}
	
	//单独保存关键词
	function saveKey($userName,$json_titleList){
		$titleList = json_decode($json_titleList,true);
		$str_title = implode(",", $titleList);
		$res = file_put_contents(POST_KEY_LOG."{$userName}_key.csv", $str_title.",", FILE_APPEND);
		return ($res == false) ? false : true;
	}
}







